﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Linq;
using Bongiozzo.Properties;

namespace Bongiozzo.Models
{
    public class Movie
    {
        public string Title;
        public string WebUrl;
        public string ThumbUrl;
    }
    
    public class KinopoiskModel
    {
        public String KinopoiskId { get; set; }
        public KinopoiskModel()
        { 
            KinopoiskId = Settings.Default.KinopoiskId;
        }
        
        private static XDocument xDoc = null; //static variable to store the result xml.
        private static IEnumerable<Movie> movies = null;
    
        public IEnumerable<Movie> GetMovies(int moviesCount)
        {
            var xml = LoadXML(moviesCount);
            
            if (xml != null)
            {
                movies = from e in xml.Element("rss").Element("channel").Descendants("item").TakeWhile((movie, index) => index < moviesCount)
                        select new Movie
                        {
                            Title = getMovieTitle(e.Element("title").Value),
                            WebUrl = getMovieUrl(e.Element("link").Value),
                            ThumbUrl = getThumbUrl(e.Element("link").Value),
                        };
            }
            return movies;
        }

        private string getThumbUrl(string p)
        {
            Regex reg = new Regex(@"^http://www\.kinopoisk\.ru/level/(\d+)/film/(\d+)/$");
            Match m = reg.Match(p);
            if (m.Success)
                return String.Format("http://st.kinopoisk.ru/images/film/{0}.jpg", m.Groups[2].Value);
            else
                return "";
        }

        private string getMovieUrl(string p)
        {
            Regex reg = new Regex(@"^http://www\.kinopoisk\.ru/level/(\d+)/film/(\d+)/$");
            Match m = reg.Match(p);
            if (m.Success)
                return String.Format("http://www.kinopoisk.ru/level/1/film/{0}/", m.Groups[2].Value);
            else
                return "";
        }

        private string getMovieTitle(string p)
        {
            Regex reg = new Regex("^Оценка фильма: «(.*)»$");
            Match m = reg.Match(p);
            if (m.Success)
                return m.Groups[1].Value;
            else
                return "";            
        }

        private XDocument LoadXML(int moviesCount)
        {
            try
            {
                var url = string.Format("http://www.kinopoisk.ru/rss/uvote-{0}.rss", KinopoiskId);
                xDoc = XDocument.Load(url);
                return xDoc;
            }
            catch
            {
                return null;
            }
        }
    }
}